<?php

namespace App\Service\ObjectStorage;

use App\Utils\Helper\GetterHelper;
use Qcloud\Cos\Client;

/**
 * 腾讯云COS服务类
 * Class TencentCloudCOSService
 * @package App\Service\ObjectStorage
 */
class TencentCloudCOSService extends ObjectStorageService implements ObjectStorageInterface {
    protected $secret_id;
    protected $secret_key;
    protected $region;
    protected $bucket;
    protected $schema;
    protected $client;

    public function __construct () {
        $this->secret_id = GetterHelper::getParameter('qcloud.cos.secretid');
        $this->secret_key = GetterHelper::getParameter('qcloud.cos.secretkey');
        $this->region = GetterHelper::getParameter('qcloud.cos.region');
        $this->bucket = GetterHelper::getParameter('qcloud.cos.bucket');
        $this->schema = GetterHelper::getParameter('qcloud.cos.schema');
        $this->init();
    }

    /**
     * 初始化
     */
    public function init () {
        $params = [
            'region'      => $this->region,
            'schema'      => $this->schema,
            'credentials' => [
                'secretId'  => $this->secret_id,
                'secretKey' => $this->secret_key,
            ],
        ];
        $this->client = new Client($params);
    }

    /**
     * 图片上传 - 表单
     * @param $file
     * @param $file_path
     * @param string[] $allow_type
     * @param int $max_size 默认上传大小为1M
     * @return array|mixed
     * @throws \Exception
     */
    public function uploadFileByFromFile ($file, $file_path, $allow_type = ['jpg', 'png', 'jpeg'], $max_size = 1048576) {
        try {
            $result = [];
            // 文件校验
            $file = $this->verifyFile($file, $file_path, $allow_type, $max_size);
            // 上传到COS
            $params = [
                'Bucket' => $this->bucket,
                'Region' => $this->region,
                'Key'    => $file->getNewFilePath(),
                'Body'   => fopen($file->getFileTmpName(), 'rb'),
            ];
            $response = $this->client->putObject($params);
            $result['key'] = $response['Key'] ?? '';
            return $result;
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
    }
}